// 获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    actionType: '新增',
    modelid: '',
    model: {
      Pictures: [],
      Detail: []
    },
    allPlaces: [],
    places: [],
    categories: [],
    maxFiles: 3,
    files: [],
    showHC: false, // 显示选择耗材
    items: [],
    itemHCs: [],
    pageIndex: 0, // 当前页Index
    totalPages: 1, // 明细页数
    pageSize: 20,
    activeId: 1,
    mainActiveIndex: 0,
    showAction: false,
    filter: {
      categoryId: 0,
      categoryName: '',
      placeId: 0,
      placeName: '',
      name: '',
      pp: '',
      gg: '',
      location: '',
      onlyStock: true,
    },
    filterHC: {
      name: '',
      pp: '',
      gg: '',
      onlyStock: true,
    },
    categoryActiveIndex: 0,
    categoryActiveId: null,
    showCategory: false,
    showPlace: false,
  },
  onLoad: function (options) {
    let _this = this;
    let _id = options.maintenanceId || '';
    _this.loadDetail(_id);
    _this.setData({
      modelid: _id,
      actionType: (_id ? "修改" : "新增")
    });
  },
  loadDetail(id) {
    let _this = this;
    const {
      filterHC
    } = _this.data;
    const _user = wx.getStorageSync(app.cache.AUTH_USER);
    app.ajax({
      url: 'StockIn/Create',
      data: {
        customerId: _user.Id,
        maintenanceId: id,
      },
      success(resp) {
        if (resp.model) {
          const _allPlaces = resp.model.AvailablePlaces || [];
          const _places = _allPlaces;
          const _categories = (resp.model.AvailableCategories.filter(m => m.PId == 0) || []).map(s => {
            var children = (resp.model.AvailableCategories.filter(m => m.PId == s.Id) || []).map(d => {
              return {
                id: d.Id,
                text: d.Text
              };
            });
            children.unshift({
              id: s.Id,
              text: s.Text,
            });
            return {
              id: s.Id,
              text: s.Text,
              children
            };
          });
          filterHC.name = resp.model.Name || '';
          filterHC.pp = resp.model.Manufacturer || '';
          filterHC.gg = resp.model.Specification || '';
          _this.setData({
            modelid: resp.model.Id,
            model: resp.model,
            filterHC,
            places: _places,
            categories: _categories,
            allPlaces: _allPlaces,
          });
        }
      }
    });
  },
  loadConsumables(push = false) {
    let _this = this;
    const {
      filterHC: {
        categoryId,
        name,
        pp,
        gg,
        onlyStock,
      },
      pageIndex,
      totalPages,
      pageSize,
      itemHCs,
      model
    } = _this.data;
    if (push && pageIndex + 1 >= totalPages) return;
    let ids = model.Detail.map(m => m.EquipmentId);
    app.ajax({
      url: 'Equipment/List',
      data: {
        categoryId,
        name,
        pp,
        gg,
        isConsumables: true,
        onlyStock,
        pageIndex: push ? pageIndex + 1 : pageIndex,
        pageSize
      },
      success(resp) {
        if (resp.result && resp.model) {
          let _lists = (resp.model||[]).map(m=>{
            m.Checked = ids.indexOf(m.Id) !== -1;
            return m;
          });
          const list = push ? [...itemHCs, ..._lists] : _lists;
          _this.setData({
            itemHCs: list,
            pageIndex:resp.PageIndex,
            totalPages:resp.TotalPages
          });
        }
      }
    });
  },
  scrolltolowerHC() {
    this.loadConsumables(true);
  },
  bindPickerChange(e) {
    this.setData({
      zrcd: e.detail.value
    });
  },
  addImage(e) {
    let _this = this;
    wx.chooseMedia({
      mediaType: ['image'],
      sourceType: ['camera'],
      sizeType: ['compressed'],
      success: function (res) {
        let _files = _this.data.files;
        if (res.tempFiles.length + _files.length > _this.data.maxFiles) {
          wx.showToast({
            icon: 'none',
            title: `最多允许上传${_this.data.maxFiles}张图片`
          });
          return;
        }
        let startIdx = _files.length;
        for (let i = 0; i < res.tempFiles.length; i++) {
          _files.push({
            img: res.tempFiles[i].tempFilePath,
            percent: 0,
            id: 0,
            unique: startIdx + i
          });
        }
        _this.setData({
          files: _files
        }, function () {
          for (let j = 0; j < res.tempFiles.length; j++) {
            _this.uploadImg(res.tempFiles[j].tempFilePath, startIdx + j);
          }
        });
      }
    });
  },
  uploadImg(file, idx) {
    let _this = this;
    var task = wx.uploadFile({
      url: `${app.apiRoot}/Picture/AsyncUpload`,
      filePath: file,
      name: 'qqfile',
      success(resp) {
        var data = JSON.parse(resp.data) //返回的是[字符串]，需要自己转为JSON格式
        let _files = _this.data.files;
        _files[idx].id = data.pictureId;
        _this.setData({
          files: _files
        });
      },
      fail(resp) {
        console.log('fail', resp);
      }
    });

    task.onProgressUpdate((res) => {
      let _files = _this.data.files;
      _files[idx].percent = res.progress;
      _this.setData({
        files: _files
      });
    });
  },
  tapImg(e) {
    let _this = this;
    let _idx = e.currentTarget.dataset.idx
    let _files = _this.data.files;
    _files.splice(_idx, 1);
    _this.setData({
      files: _files
    });
  },
  showPopupHC() {
    this.loadConsumables();
    this.setData({
      showHC: true
    });
  },
  onHCClose() {
    this.setData({
      showHC: false,
    });
  },
  doSave(e) {
    let _this = this;
    const _user = wx.getStorageSync(app.cache.AUTH_USER);
    let _imgs = '';
    let _picDone = true;
    for (let i = 0; i < _this.data.files.length; i++) {
      if (_this.data.files[i].id <= 0) {
        _picDone = false;
        break;
      } else {
        _imgs += ',' + _this.data.files[i].id;
      }
    }
    if (!_picDone) {
      app.showNotify('请等待图片上传完成');
      return;
    }
    const {
      model
    } = _this.data;
    model.CustomerId = _user.Id;
    model.SelectedPictureIds = _imgs;
    if (model.MaintenanceId <= 0) {
      app.showNotify('维修Id未找到');
      return;
    }
    if (!model.Detail || model.Detail.length === 0) {
      app.showNotify('请选择明细');
      return;
    }
    app.ajax({
      url: 'StockIn/Save',
      data: model,
      timeout: 2000,
      again: false, // 重复调用
      verifyToken: true,
      success: function (resp) {
        if (!resp.result) {
          Notify(resp.msg);
        } else {
          wx.showToast({
            title: _this.data.actionType + '成功',
            complete() {
              wx.navigateBack({
                delta: 1
              });
            }
          });
          if (resp.id > 0) {
            wx.request({
              url: `${app.apiRoot}/StockIn/SubscribeMessage`,
              method: 'POST',
              data: {
                id: resp.id,
                templateId: 'nQpdDl04GLhjY7EwrF3rk6orDUEI_WcDQ3lp5FUg09k'
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success(msgRes) {
                console.log(msgRes.data);
                // if (msgRes.data.success) {
                //   wx.showModal({
                //     title: '操作成功！',
                //     content: msgRes.data.msg,
                //   })
                // } else {
                //   wx.showModal({
                //     title: '操作失败！',
                //     content: msgRes.data.msg,
                //   })
                // }
              }
            })
          }
        }
      }
    });
  },
  doBack(e) {
    wx.navigateBack({
      delta: 1
    });
  },
  onStepperChange(e) {
    const _this = this;
    const {
      model
    } = _this.data;

    const {
      currentTarget: {
        dataset: {
          sid,
          eid,
        }
      },
      detail
    } = e;
    if (sid > 0) {
      if (detail > 0) {
        const stock = model.Detail.filter(m => m.EquipmentStockId === sid)[0];
        if (stock) {
          stock.Amount = detail;
        }
      } else {
        model.Detail = model.Detail.filter(m => m.EquipmentStockId != sid);
      }
    } else {
      if (detail > 0) {
        const equipment = model.Detail.filter(m => m.EquipmentId === eid)[0];
        if (equipment) {
          equipment.Amount = detail;
        }
      } else {
        model.Detail = model.Detail.filter(m => m.EquipmentId != eid);
      }
    }
    _this.setData({
      model
    });
  },

  onCheckChange(e) {
    const _this = this;
    const {
      model,
      items
    } = _this.data;

    const {
      currentTarget: {
        dataset: {
          id
        }
      },
      detail
    } = e;

    const stock = items.filter(m => m.Id === id)[0];
    if (stock) {
      if (detail) {
        const d = model.Detail.filter(m => m.EquipmentStockId === id)[0];
        if (!d) {
          model.Detail.push({
            Id: 0,
            EquipmentStockId: stock.Id,
            EquipmentId: stock.EquipmentId,
            Title: stock.Name + ' ' + (stock.Manufacturer || '') + ' ' + (stock.Specification || ''),
            Label: stock.Location,
            Amount: 1,
            Stock: stock.Stock,
          });
        }
      } else {
        model.Detail = model.Detail.filter(m => m.EquipmentStockId != id);
      }
      stock.Checked = detail;
    }
    _this.setData({
      model,
      items
    });
  },
  onHCCheckChange(e) {
    const _this = this;
    const {
      model,
      itemHCs
    } = _this.data;

    const {
      currentTarget: {
        dataset: {
          id
        }
      },
      detail
    } = e;

    const stock = itemHCs.filter(m => m.Id === id)[0];
    if (stock) {
      if (detail) {
        const d = model.Detail.filter(m => m.EquipmentId === id)[0];
        if (!d) {
          model.Detail.push({
            Id: 0,
            EquipmentStockId: 0,
            EquipmentId: stock.Id,
            Title: stock.Name + ' ' + (stock.Manufacturer || '') + ' ' + (stock.Specification || ''),
            Amount: 1,
            Stock: stock.Stock,
          });
        }
      } else {
        model.Detail = model.Detail.filter(m => m.EquipmentId != id);
      }
      stock.Checked = detail;
    }
    _this.setData({
      model,
      itemHCs
    });
  },
  // onDelete(e) {
  //   const _this = this;
  //   const {
  //     model
  //   } = _this.data;

  //   const {
  //     currentTarget: {
  //       dataset: {
  //         sid,
  //         eid,
  //       }
  //     }
  //   } = e;
  //   if (sid > 0) {
  //     model.Detail = model.Detail.filter(m => m.EquipmentStockId != sid);
  //   } else {
  //     model.Detail = model.Detail.filter(m => m.EquipmentId != eid);
  //   }
  //   _this.setData({
  //     model
  //   });
  // },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 输入框值变化
  onFieldChange(e) {
    const _this = this;
    const {
      filter
    } = _this.data;
    const {
      detail,
      target: {
        id
      }
    } = e;
    filter[id] = detail;
    this.setData({
      filter
    });
  },

  // 输入框值变化
  onSwitchChange(e) {
    const _this = this;
    const {
      filter
    } = _this.data;
    const {
      detail,
      target: {
        id
      }
    } = e;
    filter[id] = detail;
    this.setData({
      filter
    });
  },

  // 根据筛选条件查询
  onHCSearch() {
    const _this = this;
    _this.selectComponent('#item2').toggle();
    _this.setData({
      pageIndex: 0,
      totalPages: 1
    });
    _this.loadConsumables();
  },

  onHCCancel() {
    const _this = this;
    const {
      filterHC
    } = _this.data;
    _this.selectComponent('#item2').toggle();
    filterHC.categoryId = 0;
    filterHC.CategoryName = '';
    filterHC.name = '';
    filterHC.pp = '';
    filterHC.gg = '';
    _this.setData({
      filterHC,
      pageIndex: 0,
      totalPages: 1
    });
    _this.loadConsumables();
  },

  // 输入框值变化
  onHCFieldChange(e) {
    const _this = this;
    const {
      filterHC
    } = _this.data;
    const {
      detail,
      target: {
        id
      }
    } = e;
    filterHC[id] = detail;
    this.setData({
      filterHC
    });
  },

  // 输入框值变化
  onHCSwitchChange(e) {
    const _this = this;
    const {
      filterHC
    } = _this.data;
    const {
      detail,
      target: {
        id
      }
    } = e;
    filterHC[id] = detail;
    this.setData({
      filterHC
    });
  },

  // 显示设备分类选择框
  showCategory(e) {
    this.setData({
      showCategory: true
    });
  },

  closeCategory() {
    this.setData({
      showCategory: false
    });
  },

  onCategoryClickNav({
    detail = {}
  }) {
    this.setData({
      categoryActiveIndex: detail.index || 0
    });
  },

  onCategoryClickItem({
    detail = {}
  }) {
    const {
      filterHC,
    } = this.data;
    const categoryActiveId = detail.id;
    filterHC.categoryId = categoryActiveId;
    filterHC.CategoryName = detail.text;
    this.setData({
      categoryActiveId,
      filterHC,
      showCategory: false,
    });
  },

})